//
//  SLOAuthViewController.swift
//  langligelang
//
//  Created by 秦－政 on 2016/10/23.
//  Copyright © 2016年 pete. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD
class SLOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }

    private func setupUI(){
        // 设置背景色
        view.backgroundColor = UIColor.white
        // 设置导航
        setupNavgationBar()
    }
    private func setupNavgationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighlightedImgName: nil, title: "取消", target: self, action: #selector(cancelClick))
         navigationItem.rightBarButtonItem = UIBarButtonItem(setHighlightedImgName: nil, title: "自动填充", target: self, action: #selector(loginlClick))
        navigationItem.title = "微博登录" // 设置标题
    }
    // 监听事件 取消
    @objc private func cancelClick(){
        print("点击取消")
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    // 登录
    @objc private func loginlClick(){
        print("点击自动填充")
        // 此处需要进行js注入
        let jsString = "document.getElementById('userId').value='\(SLWBNAME)',document.getElementById('passwd').value='\(SLWBPASSWD)'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    // MARK: - 懒加载一个webView
    private lazy var webView: UIWebView = {
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(SLAPPKEY)&redirect_uri=\(SLREDIRECTURI)")!
        let request = URLRequest(url: url)
        let view = UIWebView()
        view.delegate = self
        view.loadRequest(request)
        return view
    }()
}
extension SLOAuthViewController:UIWebViewDelegate{
    // 监听将要加载的request
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // url
        let urlString = request.url?.absoluteString
        
        // 判断urlString 不为nil 而且前缀包含我们的回调页
        if let u = urlString, u.hasPrefix(SLREDIRECTURI){
            // 获取请求参数
            let query = request.url?.query
            if let q = query{
                print(q)
                // 截取 code
                let code = q.substring(from: "code=".endIndex)
                print("要的就是你",code)
//                getUserAccount(code: code)
                SLUserAccountViewModel.sharedTools.getUserAccount(code: code, finish: { (isS) in
                    if !isS{
                        print("请求失败lalalallal")
                        SVProgressHUD.showError(withStatus: "请求失败")
                        return
                    }
                    print("请求成功,跳转到欢迎界面")
                    SVProgressHUD.dismiss()
                    self.dismiss(animated: false, completion: { 
                        // 发送通知跳转到欢迎界面
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SLSWITCHROOTVCNOTI), object: nil)
                    })
                    
                })
                // 请求成功后不继续加载授权界面
//                return false
            }
        
        }
        return true
    }
    // 将要加载VebView
    func webViewDidStartLoad(_ webView: UIWebView) {
        // 开始动画
        SVProgressHUD.show()
    }
    // 网页加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // 结束动画
        SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.showError(withStatus: "网页加载失败")
    }
}
